package com.hxkj.controller;

import com.github.pagehelper.PageInfo;
import com.hxkj.client.service.UserFootprintServiceClient;
import com.hxkj.domain.enums.UserExceptionEnum;
import com.hxkj.domain.po.UserFootprint;
import com.hxkj.service.TokenService;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.exception.CustomMessageException;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.to.PageTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * created by kezhijie on 2018/9/4 11:57.
 * email to kezhijie@hxoss.com
 */
@RestController
@RequestMapping("footprint")
public class UserFootprintController {

    @Autowired
    private UserFootprintServiceClient userFootprintServiceClient;
    @Autowired
    private TokenService tokenService;

    @PostMapping("save")
    public void save(@ModelAttribute UserFootprint userFootprint) throws Exception {
        if (Objects.isNull(userFootprint) || StringUtils.isEmpty(userFootprint.getUserId()))
            throw new CustomException(UserExceptionEnum.USERINFO_INVALID);

        if (StringUtils.isEmpty(userFootprint.getSiteUrl()))
            throw new CustomException(UserExceptionEnum.FORWARD_URL_IS_NULL);

        userFootprintServiceClient.footprintSave(userFootprint);
    }

    @GetMapping("get")
    public PageInfo get(@ModelAttribute UserFootprint userFootprint, PageTo pageParam, HttpServletRequest request) throws Exception {
        String accessToken = request.getHeader("accessToken");
        if (StringUtils.isEmpty(accessToken))
            throw new CustomException(UserExceptionEnum.USERINFO_INVALID);
        String userId = tokenService.validate(accessToken).getData().getUserId();
        userFootprint.setUserId(userId);

        ParameterDataStruct<UserFootprint> parameterDataStruct = new ParameterDataStruct<>();
        parameterDataStruct.setData(userFootprint);
        parameterDataStruct.setPageTo(pageParam);

        ResultDataStruct<PageInfo> resultDataStruct = userFootprintServiceClient.footprintGet(parameterDataStruct);

        if (resultDataStruct.getCode() == 500)
            throw new CustomMessageException(resultDataStruct.getMessage());
        if (resultDataStruct.getCode() != 200)
            throw new CustomException(UserExceptionEnum.getEnumByCode(resultDataStruct.getCode()));

        return resultDataStruct.getData();
    }
}
